﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Cjc.Data.Mapping
{
	// TODO: Make public? (taken from Reflector)
	internal static class TypeHelper
	{
		// Methods
		internal static Type FindGenericType( Type definition, Type type )
		{
			while ( ( type != null ) && ( type != typeof( object ) ) )
			{
				if ( type.IsGenericType && ( type.GetGenericTypeDefinition() == definition ) )
				{
					return type;
				}
				if ( definition.IsInterface )
				{
					foreach ( Type type2 in type.GetInterfaces() )
					{
						Type type3 = FindGenericType( definition, type2 );
						if ( type3 != null )
						{
							return type3;
						}
					}
				}
				type = type.BaseType;
			}
			return null;
		}

		internal static Type GetElementType( Type enumerableType )
		{
			Type type = FindGenericType( typeof( IEnumerable<> ), enumerableType );
			if ( type != null )
			{
				return type.GetGenericArguments()[ 0 ];
			}
			return enumerableType;
		}

		internal static Type GetNonNullableType( Type type )
		{
			if ( IsNullableType( type ) )
			{
				return type.GetGenericArguments()[ 0 ];
			}
			return type;
		}

		internal static bool IsEnumerableType( Type enumerableType )
		{
			return ( FindGenericType( typeof( IEnumerable<> ), enumerableType ) != null );
		}

		internal static bool IsKindOfGeneric( Type type, Type definition )
		{
			return ( FindGenericType( definition, type ) != null );
		}

		internal static bool IsNullableType( Type type )
		{
			return ( ( ( type != null ) && type.IsGenericType ) && ( type.GetGenericTypeDefinition() == typeof( Nullable<> ) ) );
		}
	}
}
